package com.engineering.elink.service.impl;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.engineering.elink.co.BaseCo;
import com.engineering.elink.co.FileCo;
import com.engineering.elink.common.CoinEnum;
import com.engineering.elink.common.Constant;
import com.engineering.elink.common.ErrorType;
import com.engineering.elink.common.HessianResultEnum;
import com.engineering.elink.common.HessionEnum;
import com.engineering.elink.common.Pagination;
import com.engineering.elink.dao.BrowseRecordMapper;
import com.engineering.elink.dao.DetailCategoryMapper;
import com.engineering.elink.dao.FileCacheMapper;
import com.engineering.elink.dao.FileDcMapper;
import com.engineering.elink.dao.FileMapper;
import com.engineering.elink.dao.KeyWordMapper;
import com.engineering.elink.dao.OrdersMapper;
import com.engineering.elink.dao.SecondaryCategoryMapper;
import com.engineering.elink.dao.TagMapper;
import com.engineering.elink.dao.TopCategoryMapper;
import com.engineering.elink.dao.TypeMapper;
import com.engineering.elink.domain.BrowseRecord;
import com.engineering.elink.domain.Course;
import com.engineering.elink.domain.DetailCategory;
import com.engineering.elink.domain.File;
import com.engineering.elink.domain.FileCache;
import com.engineering.elink.domain.FileDc;
import com.engineering.elink.domain.KeyWord;
import com.engineering.elink.domain.Orders;
import com.engineering.elink.domain.SecondaryCategory;
import com.engineering.elink.domain.Skill;
import com.engineering.elink.domain.TopCategory;
import com.engineering.elink.hessian.CoinHessianService;
import com.engineering.elink.hessian.PersonDynamicHessianService;
import com.engineering.elink.service.FileService;
import com.engineering.elink.util.DCSTest;
import com.engineering.elink.util.JSONUtil;
import com.engineering.elink.util.tool.UUIDUtil;
import com.engineering.elink.vo.FileVo;
import com.engineering.elink.vo.FileVo2;
import com.engineering.elink.vo.HessianMessage;
import com.engineering.elink.vo.PlanVo;

@Service("fileService")
public class FileServiceImpl implements FileService {
	@Autowired
	private FileMapper fileMapper;
	@Autowired
	private TagMapper tagMapper;
	@Autowired
	private BrowseRecordMapper browseRecordMapper;
	@Autowired
	private FileDcMapper fileDcMapper;
	@Autowired
	private KeyWordMapper keyWordMapper;
	@Autowired
	private DetailCategoryMapper detailCategoryMapper;
	@Autowired
	private TypeMapper typeMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private TopCategoryMapper topCategoryMapper;
	@Autowired
	private SecondaryCategoryMapper secondaryCategoryMapper;
	@Autowired
	private  PersonDynamicHessianService  personDynamicHessianService;
	@Autowired
	private CoinHessianService coinHessianService;
	@Autowired
	private FileCacheMapper  fileCacheMapper;
	@Override
	public Map<String, Object> getFilesList(FileCo co) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<FileVo> list= new ArrayList<FileVo>();
		int count = 0;
		if(co.getMold()==0){//工程资料
            //根据co.dcId 和 co.dcType查询 fileIds
			List<Map<String, Object>> fileIdList  = fileMapper.selectFileIds(co);
     		if(fileIdList != null){
     			String fileids = "";
     			for (Map<String, Object> map2 : fileIdList) {
     				fileids+=String.valueOf(map2.get("fileId")) +",";
//     				FileVo vo = fileMapper.selectFileVo(String.valueOf(map2.get("fileId")));
//     				list.add(vo);
     			}
     			if(fileids != ""){
     				fileids = fileids.substring(0,fileids.length()-1);
     				list = fileMapper.selectFileVo(fileids);
     				count = fileMapper.selectCount(co);
     			}
     		}
		}else if(co.getMold()==1){//职业考证体系资料
			co.setTcId(4);//职业考证资料
			list= fileMapper.selectCertFileList(co);
		    count = fileMapper.selectCertFileCount(co);
		}else if(co.getMold()==3){//建筑类别资料
			co.setTcId(9);//建筑类别
			list= fileMapper.selectBuildFileList(co);
		    count = fileMapper.selectBuildFileCount(co);
		}
		map.put("list", list);
		map.put("Pagination", new Pagination(co, count));

		// 将关键词存入表中
		KeyWord kw = keyWordMapper.selectByKeyWord(co.getKeyWord());
		if (kw != null) {// 表示该关键词存在
			kw.setSearchCount(kw.getSearchCount() + 1);
			keyWordMapper.updateByPrimaryKeySelective(kw);
		} else {
			if (co.getKeyWord() != null && co.getKeyWord() != "") {
				KeyWord newKw = new KeyWord();
				newKw.setName(co.getKeyWord());
				newKw.setSearchCount(1);
				newKw.setSearchTime(new Date());
				keyWordMapper.insertSelective(newKw);
			}
		}
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> add(File file, String dcIds) {
		String fileId = UUIDUtil.getUUID();
		file.setFileId(fileId);
		file.setUploadTime(new Date());

		List<FileDc> fdc = new ArrayList<FileDc>();
		for (String dcId : dcIds.split(",")) {
			FileDc f = new FileDc();
			f.setDcId(Integer.parseInt(dcId));
			f.setFileId(fileId);
			fdc.add(f);
		}
		fileDcMapper.insertBatch(fdc);
		fileMapper.insertSelective(file);
		
		//TODO 文件备份
		
		//远程存储
		try {
			personDynamicHessianService.addPersonDynamic(HessionEnum.UPLOADDATABASE.getIndex(),file.getTypeId(),
					file.getName(),file.getIntroduction(),file.getUserId(),fileId,null);
		} catch (Exception e) {
			  Logger logger = Logger.getLogger(FileServiceImpl.class);
			  logger.info("远程添加工程资料失败"+e);
		}
//		wordToPng(String fileId, String userId,int type);
		
		new Thread() {  
		    public void run() {  
		    	 wordToPng( fileId,file.getPath(),  file.getUserId(), file.getTypeId(),1);
		    };  
		}.start();
		
		Map<String, Object> map = new HashMap<String, Object>();
		//审核成功后奖励的E币数
		
		//获取影响值
		
//		try {
//			map = coinHessianService.getCoinRule(CoinEnum.UPLOADDATABASE.getIndex());
//		} catch (Exception e) {
//			  Logger logger = Logger.getLogger(FileServiceImpl.class);
//			  logger.info("远程获取上传工程资料奖励的E币数失败"+e);
//		}
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}
  
	@Override
	public Map<String, Object> update(File file, String dcIds) {

		fileDcMapper.deleteByFileId(file.getFileId());
		
		List<FileDc> fdc = new ArrayList<FileDc>();
		for (String dcId : dcIds.split(",")) {
			FileDc f = new FileDc();
			f.setDcId(Integer.parseInt(dcId));
			f.setFileId(file.getFileId());
			fdc.add(f);
		}
		fileDcMapper.insertBatch(fdc);
		fileMapper.updateByPrimaryKeySelective(file);

		//远程更新
		try {
			personDynamicHessianService.modifyPersonDynamic(HessionEnum.MODIFYDATABASE.getIndex(),file.getTypeId(),
					file.getName(),file.getIntroduction(),file.getFileId(),file.getUserId());
		} catch (Exception e) {
			  Logger logger = Logger.getLogger(FileServiceImpl.class);
			  logger.info("远程更新工程资料失败"+e);
		}
		
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public Map<String, Object> get(String fileId, String userId) {
		FileVo2 fileVo2 = fileMapper.selectInfo(fileId, userId);
		if (fileVo2 != null) {
			// 往浏览记录表面插入数据
			if( userId != null){
				BrowseRecord br = new BrowseRecord();
				br.setFileId(fileId);
				br.setUserId(userId);
				br.setBrowseTime(new Date());
				browseRecordMapper.insertSelective(br);
				
				// 更新工程资料的浏览次数
				fileVo2.setBrowseCount(fileVo2.getBrowseCount() + 1);
				fileMapper.updateByPrimaryKeySelective(fileVo2);
			}

			// 根据上传时间查询出上一篇和下一篇
			File fpre = fileMapper.selectPre(fileVo2.getUploadTime());
			File fnext = fileMapper.selectNext(fileVo2.getUploadTime());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("file", fileVo2);
			map.put("fpre", fpre);
			map.put("fnext", fnext);
//			// 统计该作者上传共享的资料的资料
//			if( userId != null){
//				map.put("share", fileMapper.getShare(fileVo2.getUserId()));
//				map.put("shareCount",fileMapper.countUploadFileByUserId(fileVo2.getUserId(),null));
//			}else{//用户没有登录
//				map.put("share", null);
//				map.put("shareCount",0);				
//			}
			
			// 查询该文件的分类
			TopCategory top = topCategoryMapper.selectByPrimaryKey(fileVo2.getTcId());
			SecondaryCategory sec = secondaryCategoryMapper.selectByPrimaryKey(fileVo2.getScId());
			List<DetailCategory>  detailList = detailCategoryMapper.selectListByFileId(fileVo2.getFileId());
			Map<String, Object> category = new HashMap<String, Object>();
			category.put("topCategory", top);
			category.put("secCategory", sec);
			category.put("detailCategory", detailList);
			
			map.put("category", category);
			return JSONUtil.getJSON(ErrorType.SUCCESS, map);

		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> getShare(String fileId) {
		File file = fileMapper.selectByPrimaryKey(fileId);
		if (file != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			// 统计该作者上传共享的资料的资料
//			if( userId != null){
				map.put("share", fileMapper.getShare(file.getUserId()));
				map.put("shareCount",fileMapper.countUploadFileByUserId(file.getUserId(),null));
//			}else{//用户没有登录
//				map.put("share", null);
//				map.put("shareCount",0);				
//			}
			return JSONUtil.getJSON(ErrorType.SUCCESS, map);

		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}
	
	@Override
	public Map<String, Object> getPreviewPngOfFile(String fileId, String userId,int type) {
		// 首先查找该文件是否在缓存中
		Map<String, Object>map = new HashMap<String, Object>();
		if(type == 1){//资料
			map = fileMapper.selectFile(fileId);
		}else{
			map = fileMapper.selectThesis(fileId);
		}
		if(map == null){
			return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR); 
		}
		
//		System.out.println(Constant.DOWNLOAD_URL+ (String) map.get("path") );
//		 if(!new java.io.File(Constant.DOWNLOAD_URL+ (String) map.get("path") ).exists()){
//			 return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR); 
//		 }
		
		List<FileCache>  fc = fileCacheMapper.selectByPrimaryKey(fileId);
		String path = "";
		int pageCount = 0;
		String convertByUrl = "";
		JSONObject jsStr = null;
		String previewPath = "";
		boolean urlFlag = true;
		if (fc.size() == 0) {// 不存在则插入记录
			FileCache fileCache = new FileCache();
			fileCache.setFileId(fileId);
			int fileType = 10;
			String ext = ".png";
			if ( (int)map.get("type") == 14 || (int)map.get("type")  == 15) {// 文档
				fileType = 5;
			} else if ((int)map.get("type")  == 16) {// 压缩文件
				fileType = 19;
			}else if ((int)map.get("type")  == 1){ //word文档
				fileType = 6;
				ext = ".jpg";
			}
			do {
				// 网络转换
				String officePath = (String) map.get("path") ;
				convertByUrl = DCSTest.sendPost(Constant.OFFICE_SERVER_IP,"downloadUrl="+Constant.DOWNLOAD_URL+""+officePath + "&convertType=" + fileType+
						"&showFooter=1&isDelSrc =1&appendPath="+officePath.substring(6, 14)+"&destinationName="+officePath.substring(officePath.indexOf(".")-32,officePath.indexOf(".")));
				System.out.println("转换结果"+convertByUrl);
				jsStr = JSONObject.parseObject(convertByUrl);
				System.out.println("转换结果1"+jsStr);
				if (jsStr != null) {
					urlFlag = false;
				}
				
			} while (urlFlag);

			if (Integer.parseInt(jsStr.getString("result")) == 0) {// 转换成功则插入数据
				String oldPath  = jsStr.getString("data").substring(1,	jsStr.getString("data").length() - 1).replaceAll("\"", "");
				if(fileType == 19){//rar文件
					path = oldPath;
					pageCount = 1;
				}else{
					//路径需要排序
					pageCount = jsStr.getString("data").split(",").length;
					int[] sort =  new int[pageCount];
//					for (int i = 0; i < pageCount; i++) {
//						sort[i] = Integer.parseInt( oldPath.split(",")[i].substring(oldPath.split(",")[i].lastIndexOf("/")+1,oldPath.split(",")[i].length()-4));;
//					}
//					Arrays.sort(sort);
					for (int i = 0; i < sort.length; i++) {
						path +=oldPath.split(",")[0].substring(0,oldPath.split(",")[0].lastIndexOf("/")+1) +(i+1)+ext+"#";
					}		
					path = path.substring(0,path.length()-1);
				}
				fileCache.setPreviewPath(path);
				fileCache.setPageCount(pageCount);
				fileCache.setType(type);
				fileCacheMapper.insertSelective(fileCache);
			}
			
			if (Integer.parseInt(jsStr.getString("result")) == 18) {// 文件下载失败
				return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR);
			}
		} else {
			path = fc.get(0).getPreviewPath();
			pageCount = fc.get(0).getPageCount();
		}
		
		if (path.split("#").length > 1) {// 文件超过1页
			if (userId == null) {// 只能够预览2页
				for (int i = 0; i < Constant.FILE_PREVIEW_COUNT; i++) {
					previewPath += path.split("#")[i] + ",";
				}
				previewPath = previewPath.substring(0, previewPath.length() - 1);
			}else{
				previewPath = path;
			}
		} else { // 否则就显示全部
			previewPath = path;
		}
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("path", previewPath);
		map2.put("pageCount", pageCount);
		return JSONUtil.getJSON(ErrorType.SUCCESS, map2);
	}
	
	@Override
	public Map<String, Object> getDownLoadRank(int count,int mold) {
		return JSONUtil.getJSON(ErrorType.SUCCESS,fileMapper.getDownLoadRank(count,mold));
	}

	@Override
	public Map<String, Object> getRelevant(String fileId, int count) {
		File file = fileMapper.selectByPrimaryKey(fileId);
		if (file != null) {
			// 根据一级分类和二级分类去找相关的工程资料
			return JSONUtil.getJSON(ErrorType.SUCCESS,fileMapper.selectRelevantList(file.getTcId(),file.getScId(), count));
		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> getLike(String fileId ,int count) {
		File file = fileMapper.selectByPrimaryKey(fileId);
		if (file != null) {
			// 找到详细分类
			List<FileDc> fileDcList = fileDcMapper.selectByFileId(fileId);
			String dc = "";
			for (FileDc fileDc : fileDcList) {
				dc += fileDc.getDcId() + ",";
			}
			if(dc != ""){
				dc = dc.substring(0, dc.length() - 1);
			}
			return JSONUtil.getJSON(ErrorType.SUCCESS,fileMapper.getLike(dc, file.getTagIds(), count));
		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> getKeyWord(int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS,keyWordMapper.getKeyWord(count));
	}

	@Override
	public Map<String, Object> getRelevantType(String fileId, int count) {
		File file = fileMapper.selectByPrimaryKey(fileId);
		if (file != null) {
			// 找到详细分类
			List<FileDc> fileDcList = fileDcMapper.selectByFileId(fileId);
			String dc = "";
			for (FileDc fileDc : fileDcList) {
				dc += fileDc.getDcId() + ",";
			}
			if (dc != "") {
				dc = dc.substring(0, dc.length() - 1);
			}
			return JSONUtil.getJSON(ErrorType.SUCCESS, detailCategoryMapper.selectInfoClassify(dc, file.getScId(), count));
		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> download(HttpServletResponse response,HttpServletRequest request, String userId, String fileId)throws IOException {
		File file = fileMapper.selectByPrimaryKey(fileId);
		if(file != null){
			HessianMessage msg  = coinHessianService.modifyCoin(fileId, CoinEnum.DOWNLOADDATABASE.getIndex(), (Float.valueOf(file.getPrice())).intValue(), userId, file.getUserId());
			if(msg.getCode() == HessianResultEnum.Success.getIndex()){//请求成功
				// 生成订单
				Orders order = new Orders();
				order.setFileId(fileId);
				order.setTime(new Date());
				order.setUserId(userId);
				order.setOrderId( UUIDUtil.getUUID());
				ordersMapper.insertSelective(order);
				
				BufferedInputStream bis = null;
				HttpURLConnection httpUrl = null;
				URL url = null;
				// 建立链接
				url = new URL(Constant.DOWNLOAD_URL+file.getPath());
				httpUrl = (HttpURLConnection) url.openConnection();
				// 连接指定的资源
				httpUrl.connect();
				// 获取网络输入流
				bis = new BufferedInputStream(httpUrl.getInputStream());
//				String fil = "/WEB-INF/ceshi.pdf";
				java.io.File fileLoad = new java.io.File(Constant.DOWNLOAD_URL+file.getPath());
				response.setContentType("multipart/form-data"); //设置文件ContentType类型，这样设置，会自动判断下载文件类型
				response.setHeader("Content-Disposition", "attachment;filename="+fileLoad.getName());
				ServletOutputStream  o = response.getOutputStream();
				byte b[] = new byte[1024];

				int n = 0;
				while ((n =bis.read(b)) != -1) {
					o.write(b, 0, n);
				}
				o.close();  
				o.flush(); 
				bis.close();
				httpUrl.disconnect();
				
				//更新资料的下载次数
				file.setDownloadCount(file.getDownloadCount()+1);
				fileMapper.updateByPrimaryKeySelective(file);
				
				//远程添加个人动态
				try {
					personDynamicHessianService.addPersonDynamic(HessionEnum.DOWNLOADDATABASE.getIndex(),file.getTypeId(),
					file.getName(),file.getIntroduction(),userId,file.getFileId(),file.getUserId());
				} catch (Exception e) {
					 Logger logger = Logger.getLogger(FileServiceImpl.class);
					 logger.info("远程添加个人动态（下载资料）失败"+e);
				}
				
				return JSONUtil.getJSON(ErrorType.SUCCESS);
			}else{
				return JSONUtil.getJSON(ErrorType.REWARD_ERROR,msg.getMsg());
			}
		}else{
			return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR);
		 }
	}

	@Override
	public Map<String, Object> getMyUploadFile(BaseCo co, String userId,String keyWord) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", fileMapper.getUploadFileByUserId(co, userId,keyWord));
		map.put("Pagination",new Pagination(co, fileMapper.countUploadFileByUserId(userId,keyWord)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> getMyDownLoadFile(BaseCo co, String userId,String keyWord) {
		Map<String, Object> map = new HashMap<String, Object>();
//		List<Map<String, Object>> fileIdList  = ordersMapper.selectFileIds(co, userId,keyWord);
//		if(fileIdList != null){
//			String fileids = "";
//			for (Map<String, Object> map2 : fileIdList) {
//				fileids+=String.valueOf(map2.get("fileId")) +",";
//			}
// 			if(fileids != ""){
// 				fileids = fileids.substring(0,fileids.length()-1);
 				map.put("list", fileMapper.selectMyDownLoadFile(co, userId,keyWord));
 				map.put("Pagination",new Pagination(co, ordersMapper.countMyDownLoadFile(userId,keyWord)));
 				return JSONUtil.getJSON(ErrorType.SUCCESS, map);
// 			}
//		}
//		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public Map<String, Object> getPlanList(int hierId, int gradeId) {
		 PlanVo baseInfo =   fileMapper.getBaseInfo(hierId,gradeId);
		 List<Skill> skillList =  fileMapper.getSkillList(hierId,gradeId);
		 List<Course> courseList =  fileMapper.getCourseList(hierId,gradeId);
		 List<File> filelList =  fileMapper.getFileList(hierId,gradeId);
//		PlanVo pv = new PlanVo();
		
		 baseInfo.setSkillList(skillList);
		 baseInfo.setCourseList(courseList);
		 baseInfo.setFileList(filelList);
		return JSONUtil.getJSON(ErrorType.SUCCESS, baseInfo);
	}

	@Override
	public Map<String, Object> getDatabaseList(int scId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> home = fileMapper.selectDatabaseListOfHome(scId);
		List<Map<String, Object>> international = fileMapper.selectDatabaseListOfInternational();
		map.put("home", home);
		map.put("international", international);
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> getFileBest(int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS, fileMapper.selectFileBest(count));
	}

	@Override
	public Map<String, Object> getFileSystem(int count) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fileSystem", fileMapper.selectFileSystem(count));
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}
	
	@Override
	public Map<String, Object> getFile(int count) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> fileSystem =  fileMapper.selectScid(count);
		String scId = "";
		for (Map<String, Object> map2 : fileSystem) {
			scId +=map2.get("scId")+",";
		}
		map.put("file", fileMapper.selectCertFile(count,scId.substring(0, scId.length()-1)));
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}
	
	
	@Override
	public Map<String, Object> getHotFile(int scId, int dcId, int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS, fileMapper.selectHotFile(scId,dcId,count));
	}
	
	public static TreeMap<java.io.File, LinkedList<java.io.File>> dirFiles = new TreeMap<java.io.File, LinkedList<java.io.File>>();
	public static void getDirectoryFiles(java.io.File dir) {
		if (!dir.isDirectory()) {
			return;
		}
		LinkedList<java.io.File> files = new LinkedList<java.io.File>();
		java.io.File[] filesinDir = dir.listFiles();
		if (filesinDir.length > 0) {
			for (int i = 0; i < filesinDir.length; i++) {
				String fileName = filesinDir[i].getName();
				if (!filesinDir[i].isDirectory() && !fileName.endsWith(".rar") ) {
					files.add(filesinDir[i]);
				}else{
					files.remove(filesinDir[i]);
				}
			}
		} else {
			dirFiles.put(dir, null);
			return;
		}
		dirFiles.put(dir, files);
		for (int i = 0; i < filesinDir.length; i++) {
			if (filesinDir[i].isDirectory()) {
				getDirectoryFiles(filesinDir[i]);

			}
		}

	}
	
//	public static void main(String[] args) {
//		getDirectoryFiles(new java.io.File(Constant.OUTPUT));
//		Iterator<java.io.File> iterator =dirFiles.keySet().iterator();
//        while (iterator.hasNext()){
//            java.io.File dir = iterator.next();
//            LinkedList<java.io.File> fileInDir = dirFiles.get(dir);
//            if (fileInDir != null) {
//                Iterator<java.io.File> it = fileInDir.iterator();
//                int num = 0;
//                while (it.hasNext()){
////                	java.io.File file = new java.io.File(it.next().getAbsolutePath());
////                	if(file.getName().endsWith(".pdf")){
//                		num ++;
//                		System.out.println(num);
//                		System.out.println(it.next().getAbsolutePath());
////                	}else {
////                		System.out.println(1);
////                	}
//
//                }
//            }
//        }   
//	}


	
//	@Override
//	public Map<String, Object> getTest() {
//		new Thread() {  
//		    public void run() {  
//		       bb();
//		    };  
//		}.start();
//		Map<String, Object> map = new HashMap<String, Object>();
//		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
//	}
	
	@Transactional
	public  Map<String, Object> wordToPng(String fileId,String filePath,String userId,int type,int cacheType){
		int pageCount = 0;
		String convertByUrl = "";
		JSONObject jsStr = null;
		String path = "";
		boolean urlFlag = true;
			FileCache fileCache = new FileCache();
			fileCache.setFileId(fileId);
			int fileType = 10;
			String ext = ".png";
			if ( type == 14 || type== 15) {// 文档
				fileType = 5;
			} else if (type == 16) {// 压缩文件
				fileType = 19;
			}else if (type == 1){ //word文档
				fileType = 6;
				ext = ".jpg";
			}
			System.out.println("转换路径"+Constant.DOWNLOAD_URL+""+filePath);
			do {
				// 网络转换
				convertByUrl = DCSTest.sendPost(
						Constant.OFFICE_SERVER_IP,
						"downloadUrl="+Constant.DOWNLOAD_URL+""+filePath + "&convertType=" + fileType+"&showFooter=1&isDelSrc =1"
								+ "&showFooter=1&isDelSrc =1&appendPath="+filePath.substring(6, 14)+"&destinationName="+filePath.substring(filePath.indexOf(".")-32,filePath.indexOf(".")));
				System.out.println("转换结果"+convertByUrl);
				jsStr = JSONObject.parseObject(convertByUrl);
				System.out.println("转换结果1"+jsStr);
				if (jsStr != null) {
					urlFlag = false;
				}
			} while (urlFlag);

			if (Integer.parseInt(jsStr.getString("result")) == 0) {// 转换成功则插入数据
				String oldPath  = jsStr.getString("data").substring(1,	jsStr.getString("data").length() - 1).replaceAll("\"", "");
				if(fileType == 19){//rar文件
					path = oldPath;
					pageCount = 1;
				}else{
					//路径需要排序
					pageCount = jsStr.getString("data").split(",").length;
					int[] sort =  new int[pageCount];
//					for (int i = 0; i < pageCount; i++) {
//						sort[i] = Integer.parseInt( oldPath.split(",")[i].substring(oldPath.split(",")[i].lastIndexOf("/")+1,oldPath.split(",")[i].length()-4));
//					}
//					Arrays.sort(sort);
					for (int i = 0; i < sort.length; i++) {
						path +=oldPath.split(",")[0].substring(0,oldPath.split(",")[0].lastIndexOf("/")+1) +(i+1)+ext+"#";
					}		
					path = path.substring(0,path.length()-1);
				}
				fileCache.setPreviewPath(path);
				fileCache.setPageCount(pageCount);
				fileCache.setType(cacheType);
				fileCacheMapper.insertSelective(fileCache);
				return JSONUtil.getJSON(ErrorType.SUCCESS);
			}
			if (Integer.parseInt(jsStr.getString("result")) == 18) {// 文件下载失败
				return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR);
			}
		return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR);
	}

	@Override
	public Map<String, Object> getTest(String lujing) {

		getDirectoryFiles(new java.io.File(lujing));
		Iterator<java.io.File> iterator =dirFiles.keySet().iterator();
        while (iterator.hasNext()){
            java.io.File dir = iterator.next();
            LinkedList<java.io.File> fileInDir = dirFiles.get(dir);
            if (fileInDir != null) {
                Iterator<java.io.File> it = fileInDir.iterator();
                int num = 0;
                while (it.hasNext()){
                    num ++;
                	System.out.println(num);
                	String path =it.next().getAbsolutePath();
                	System.out.println(path);
                	java.io.File file = new java.io.File(path);
                	if(!file.getName().endsWith(".rar")){
                		List<File> f = fileMapper.selectByPath(file.getName().substring(0,file.getName().indexOf(".")));
                		if(f!=null &&f .size() != 0){
                			//判断缓存里面是否有
                			List<FileCache> fc =  	fileCacheMapper.selectByPrimaryKey(f.get(0).getFileId());
                			if(fc.size() ==0){//如果缓存不存在
                				wordToPng( f.get(0).getFileId(), f.get(0).getPath(), f.get(0).getUserId(), f.get(0).getTypeId(),1);
//                				if((int)map.get("code") == 0 ){
//                					//测试.删除文件
//                					if(new java.io.File(path).exists()){
//                						new java.io.File(path).delete();
//                					}
//                				}
                			}
                		}
                	}
                }
            }
        }   
		return null;
	}

	
	@Override
	public Map<String, Object> getTest2(String lujing) {

		getDirectoryFiles(new java.io.File(lujing));
		Iterator<java.io.File> iterator =dirFiles.keySet().iterator();
        while (iterator.hasNext()){
            java.io.File dir = iterator.next();
            LinkedList<java.io.File> fileInDir = dirFiles.get(dir);
            if (fileInDir != null) {
                Iterator<java.io.File> it = fileInDir.iterator();
                int num = 0;
                while (it.hasNext()){
                    num ++;
                	System.out.println(num);
                	String path =it.next().getAbsolutePath();
                	System.out.println(path);
                	java.io.File file = new java.io.File(path);
                	if(!file.getName().endsWith(".rar")){
                		List<Map<String, Object>> f = fileMapper.selectByPath2(file.getName().substring(0,file.getName().indexOf(".")));
                		if(f!=null &&f .size() != 0){
                			//判断缓存里面是否有
                			List<FileCache> fc =  	fileCacheMapper.selectByPrimaryKey(f.get(0).get("thesisId").toString());
                			if(fc.size() ==0){//缓存不存在
                    		    wordToPng( f.get(0).get("thesisId").toString(), f.get(0).get("path").toString(), f.get(0).get("userId").toString(), (int)(f.get(0).get("typeId")),2);
//                				if((int)map.get("code") == 0 ){
//                					//测试.删除文件
//                					if(new java.io.File(path).exists()){
//                						new java.io.File(path).delete();
//                					}
//                				}
                			}
                		}
                	}
                }
            }
        }   
		return null;
	}
	
	 public static void main(String[] args) throws IOException {     
//		 String str = "/file/20161109/a673bed2db8e4d07a55978b25f50ad0d.doc";
//		 System.out.println(str.substring(6, 14));
		 String oldPath= "http://localhost:8080/20170309/01372fbb5e6c4501b8921adc77b745c9/01372fbb5e6c4501b8921adc77b745c9_1.png,http://localhost:8080/20170309/01372fbb5e6c4501b8921adc77b745c9/2.png,http://localhost:8080/20170309/01372fbb5e6c4501b8921adc77b745c9/3.png,http://localhost:8080/20170309/01372fbb5e6c4501b8921adc77b745c9/4.png";
		 System.out.println(Integer.parseInt( oldPath.split(",")[0].substring(oldPath.split(",")[0].lastIndexOf("/")+1,oldPath.split(",")[0].length()-4)));
//		 
//		 Map<String, Object> map = new HashMap<String, Object>();
//		 map.put("path", "/file/20161109/0b860e698bd94fb7a385b8ba63474fbd.pdf");
//		 String path1 = (String) map.get("path");
//		 System.out.println(path1);
//		 System.out.println(path1.substring(path1.indexOf(".")-32,path1.indexOf(".")));
//		 
//		 System.exit(0);
//		 
//	     long a = System.currentTimeMillis();//记录开始时间
//	      
//	     LinkedList list = new LinkedList();
//	     java.io.File dir = new java.io.File(Constant.OUTPUT);
//	     java.io.File[] file = dir.listFiles();//存放的是一级目录下的文件以及文件夹
//	      
//	     for (int i = 0; i < file.length; i++) {
//	         if (file[i].isDirectory()){
//	             list.add(file[i]);//如果是文件夹就加到list中
//	         } else{
//	             System.out.println(file[i].getAbsolutePath());//如果是文件就输出绝对路径
//	         }
//	     }
//	     java.io.File tmp;
//	     while (!list.isEmpty()) {//遍历list中的文件夹
//	         tmp = (java.io.File) list.removeFirst();//移除并返回此列表的第一个元素
//	         if (tmp.isDirectory()) {
//	             file = tmp.listFiles();//存放的是二级目录下的文件以及文件夹
//	             if (file == null){
//	            	 continue;//如果文件夹为空就跳出，进入下一个文件夹的遍历
//	             }
//	             String path = "";
//	             System.out.println(file.length);
//	             if(file.length >0){
////	            	 System.out.println(file[0].getAbsolutePath());
//	            	 String like = file[0].getAbsolutePath().substring(file[0].getAbsolutePath().lastIndexOf("\\")+1, file[0].getAbsolutePath().lastIndexOf("_"));
//	            	 for (int i = 0 ;i < file.length; i++) {//遍历二级目录下的文件夹
//	            		 if (file[i].isDirectory()){
//	            			 list.add(file[i]);//如果是文件夹就加入到list中，会在下次循环中继续调用文件夹下的文件或者文件夹
//	            		 } else{
//	            			 String str =  file[i].getAbsolutePath().replace("\\", "/").replace("F:/office", "http://116.62.10.111/office/output");
//	            			 System.out.println(str);
////	            			 System.out.println(str.split(".")[0]);
////	            			 path += str.substring(0, str.indexOf("_"))+"_"+(i+1)+str.substring(str.indexOf("."),str.length())+"#";   
////	            			 System.out.println(str.substring(str.lastIndexOf("."),str.length()));
////	            			 System.out.println(str.substring(0, str.indexOf("_"))+"_"+(i+1)+str.substring(str.indexOf("."),str.length()));
//	            		 }
//	            	 }
//	             }
//					
////           	     System.out.println(file.length);
////	             System.out.println(path);
//	         } else {
////	             System.out.println(tmp.getAbsolutePath());
//	         }
//	     }
//	      
//	     System.out.println(System.currentTimeMillis() - a);//打印遍历的时间
	}
}
